package verbindung;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import org.apache.log4j.Logger;

/**
 * 
 * 
 */
public class DBDClientText implements DBDClient {

	private Socket dbdsocket;
	private DataOutputStream out;
	private DataInputStream in;
	private BufferedReader bufread;
	private Logger logger;
	
	
	

	public DBDClientText(String server, int port)
	{
		logger = Logger.getLogger(DBDClientText.class);
		
		logger.info("Connecting to server "+server+":"+port);
		try{
			dbdsocket = new Socket(server, port);
			out = new DataOutputStream(dbdsocket.getOutputStream());
			in = new DataInputStream(dbdsocket.getInputStream());
			bufread = new BufferedReader(new InputStreamReader(in));
		}
		catch(Exception e)
		{
			logger.error("Can not connect to server "+server+" on port "+port);
		}
	}
	
	public int getVar(String name)
	{
		logger.info("Get Var "+name);
		try{
			out.writeBytes("?"+name+"\n");

			String line = bufread.readLine();
			
			logger.info("Receiving: "+line);
			
			String[] split = line.split(" ");
			
			if(split.length==2)
				return Integer.parseInt(split[1]);
			else
				logger.error("Illegal return by server");
			
			return 0;
		}catch(Exception e)
		{
			logger.error("getVar: Connection to server lost");
		}
		
		return 0;
	}

	public void setVar(String name, int val)
	{
		logger.info("Set Var "+name+" "+val);
		try{
			out.writeBytes(name+" "+val+"\n");

		}catch(Exception e)
		{
			logger.error("setVar: Connection to server lost");
		}
		
	}
	
	/**
	 * 
	 * @param lokname
	 * @param speed
	 */
	public void sendLokCommand(String lokname, int speed)
	{
		try
		{
			out.writeBytes("GO "+lokname+" "+speed+"\n");
		}catch(Exception e)
		{
			logger.error("setVar: Connection to server lost");
		}
	}

	public void close()
	{
		logger.info("Closing server connection");
		try {
			in.close();
			out.close();
			dbdsocket.close();
		} catch (IOException e) {
			logger.error("close: Error while closing server connection");
		}
		
		
	}
	
	public DBDCallback subscribeVar(String name, DBDCallback cb)
	{
		return null;
	}

	public void unsubscribeVar(String name)
	{
		
	}
	
	

}
